package plan

import (
	"mini-sql/expression"
	"mini-sql/model"
)

type WherePlanNode struct {
	source          PlanNode
	selectStatement *model.SelectStatement
}

func NewWherePlanNode(source PlanNode, selectStatement *model.SelectStatement) PlanNode {
	return &WherePlanNode{
		source:          source,
		selectStatement: selectStatement,
	}
}

func (node *WherePlanNode) Prepare() error {
	return node.source.Prepare()
}

func (node *WherePlanNode) GetNextTuple() (*model.TableTuple, error) {
	for {
		tuple, err := node.source.GetNextTuple()
		if err != nil {
			return nil, err
		}
		if tuple == nil {
			return nil, nil
		}
		if node.matchWhere(tuple) {
			return tuple, nil
		}
	}
}

func (node *WherePlanNode) matchWhere(tuple *model.TableTuple) bool {
	where := node.selectStatement.WhereClause
	if where == nil {
		return true
	}

	value := expression.EvalExpr(where, tuple)
	return value.ToBool()
}
